<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 警告区域 -->
      <el-alert show-icon title="注意：只允许为第三级分类设置相关参数！" type="warning" effect="dark" :closable="false"></el-alert>

      <!-- 商品分类的级联选择器 -->
      <div class="cascader-box">
        <span>选择商品分类：</span>
        <!-- 级联选择器 -->
        <el-cascader v-model="cascaderValue" :options="catelist" :props="cascaderProps" @change="onCascaderChange"></el-cascader>
      </div>

      <!-- tabs 页签区域 -->
      <el-tabs type="border-card" v-model="activeName" @tab-click="onTabClick">
        <el-tab-pane label="动态参数" name="many">
          <!-- 添加参数的按钮 -->
          <el-button size="mini" type="primary" :disabled="isBtnDisabled" @click="addDialogVisible = true">添加参数</el-button>
          <!-- 动态参数表格 -->
          <el-table :data="manyTableData" border stripe>
            <!-- 展开列 -->
            <el-table-column type="expand">
              <template v-slot="scope">
                <!-- 循环渲染 tag 标签 -->
                <el-tag v-for="(item, i) in scope.row.attr_vals" :key="i" closable @close="onTagClose(i, scope.row)">{{item}}</el-tag>
                <!-- 文本输入框 -->
                <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)">
                </el-input>
                <!-- 按钮 -->
                <el-button v-else size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template v-slot="scope">
                <el-button size="mini" type="primary" icon="el-icon-edit">编辑</el-button>
                <el-button size="mini" type="danger" icon="el-icon-delete">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <!-- 添加属性的按钮 -->
          <el-button size="mini" type="primary" :disabled="isBtnDisabled" @click="addDialogVisible = true">添加属性</el-button>
          <!-- 静态属性表格 -->
          <el-table :data="onlyTableData" border stripe>
            <!-- 展开列 -->
            <el-table-column type="expand">
              <template v-slot="scope">
                <!-- 循环渲染 tag 标签 -->
                <el-tag v-for="(item, i) in scope.row.attr_vals" :key="i" closable @close="onTagClose(i, scope.row)">{{item}}</el-tag>
                <!-- 文本输入框 -->
                <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)">
                </el-input>
                <!-- 按钮 -->
                <el-button v-else size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="属性名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template v-slot="scope">
                <el-button size="mini" type="primary" icon="el-icon-edit">编辑</el-button>
                <el-button size="mini" type="danger" icon="el-icon-delete">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加的对话框 -->
    <el-dialog :title="'添加' + titleText" :visible.sync="addDialogVisible" width="50%" @close="onAddDialogClose">
      <!-- 添加的表单 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addNewParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 所有商品分类数据列表
      catelist: [],
      // 级联选择器绑定到的数组
      cascaderValue: [],
      cascaderProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      activeName: 'many',
      manyTableData: [],
      onlyTableData: [],
      // 控制添加对话框的显示与隐藏
      addDialogVisible: false,
      // 添加表单的数据绑定对象
      addForm: {
        // 参数的名称
        attr_name: ''
      },
      // 添加表单的校验规则对象
      addFormRules: {
        attr_name: [{ required: true, message: '请输入参数名称', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getCateList()
  },
  computed: {
    // 动态计算添加按钮的禁用状态
    isBtnDisabled() {
      return this.cascaderValue.length !== 3
    },
    // 当前选中的三级分类的Id
    cateId() {
      if (this.cascaderValue.length === 3) {
        return this.cascaderValue[2]
      }
      return null
    },
    // 动态计算对话框的标题文本
    titleText() {
      return this.activeName === 'many' ? '动态参数' : '静态属性'
    }
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error('获取商品分类失败！')

      this.catelist = res.data
      // console.log(this.catelist)
    },
    // 监听级联选择器选中项变化的事件
    onCascaderChange() {
      // 判断是否选中了三级分类
      if (this.cascaderValue.length !== 3) {
        this.cascaderValue = []
        this.manyTableData = []
        this.onlyTableData = []
        this.$message.warning('只允许为第三级分类设置相关参数！')
        return
      }

      // console.log(this.cascaderValue)
      // 发起请求，获取对应三级分类下动态或静态参数的值
      this.getParams()
    },
    // tab 页签的点击事件处理函数
    onTabClick() {
      console.log(this.activeName)
      this.getParams()
    },
    // 获取动态或静态参数的值
    async getParams() {
      // 判断用户是否选择了三级分类的Id，如果没有，则退出后续代码的执行
      if (!this.cateId) return
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
        params: {
          sel: this.activeName
        }
      })

      if (res.meta.status !== 200) return this.$message.error('获取参数失败！')

      // 在把数据赋值到 data 之前，对服务器返回的数据进行处理
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : []
        // 为当前 row 挂载 inputVisible 和 inputValue 两个自定义属性
        item.inputVisible = false
        item.inputValue = ''
      })

      // 把数据存储到 data 中供页面使用
      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }

      console.log(this.manyTableData)
    },
    // 监听添加对话框的关闭事件
    onAddDialogClose() {
      this.$refs.addFormRef.resetFields()
    },
    // 添加新参数
    addNewParams() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return

        const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, {
          attr_name: this.addForm.attr_name,
          attr_sel: this.activeName
        })

        if (res.meta.status !== 201) return this.$message.error('添加分类参数失败！')

        this.$message.success('添加分类参数成功！')
        this.getParams()
        this.addDialogVisible = false
      })
    },
    // 文本框失去焦点或摁下enter键触发这个函数
    handleInputConfirm(row) {
      // 如果输入的内容为空，则清空文本框并隐藏
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      // 如果文本框内容不为空，则进行后续的业务处理
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false

      this.saveAttrToStorage(row)
    },
    // 将 attr_vals 保存到数据库中
    async saveAttrToStorage(row) {
      const { data: res } = await this.$http.put(`categories/${row.cat_id}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(',')
      })

      if (res.meta.status !== 200) return this.$message.error('修改失败！')
      this.$message.success('修改成功！')
    },
    // 展示文本框
    showInput(row) {
      row.inputVisible = true
      // 异步任务
      // this.$nextTick() 中的代码，会在页面重新渲染完毕之后，再执行
      this.$nextTick(_ => {
        // 让文本框自动获取焦点
        // console.log(this.$refs.saveTagInput)
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    onTagClose(i, row) {
      // 数组的 splice() 方法会修改原数组
      row.attr_vals.splice(i, 1)
      // 做了一下代码的【重构】  refactory
      this.saveAttrToStorage(row)
    }
  }
}
</script>

<style lang="less" scoped>
.cascader-box {
  margin: 20px 0;
}

.el-cascader {
  width: 300px;
}

.el-tag {
  margin: 5px;
}

.input-new-tag {
  width: 120px;
}
</style>